package com.eims.sls_app.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import bls.juejin.cn.R;
import com.eims.sls_app.dataaccess.Lottery;
import com.eims.sls_app.dataaccess.LotteryContent;
import com.eims.sls_app.dataaccess.Schemes;
import com.eims.sls_app.ui.adapter.MyBetLotteryAdapter;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.AppTools;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.Arith;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.LotteryHelp;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.utils.NumberTools;
import com.eims.sls_app.view.MyGridView;
import com.eims.sls_app.view.MyListView2;
import com.eims.sls_app.view.MyToast;

import java.util.ArrayList;
import java.util.List;

/**
 * cp 普通投注 订单详情
 * 
 * @author SLS003
 */
public class MyCommonLotteryInfo_other extends MyBaseActivity implements OnClickListener {
	private ScrollView scrollView;
	private TextView tv_lotteryName, tv_money, tv_state, tv_winMoney, tv_count,
			tv_time, tv_orderId, tv_betType, tv_tishi, tv_lotteryNum, tv_name,
			tv_yong, tv_scheme, tv_buyCount, tv_title, tv_content, tv_bei,
			tv_winMoney3, tv_lotteryName_issue, tv_info_tip;
	private ImageView img_logo, ll_divider;
	private LinearLayout ll_numberCount;
	private ImageButton betinfo_hide_btn, btn_back;
	private MyListView2 mListView;

	private MyBetLotteryAdapter adapter;

	private MyGridView gv_winNumber;

	private Schemes scheme;

	private RelativeLayout rl_join1, rl_join2;

	private MyAsynTask myAsynTask;

	private String[] numbers;
	private List<String> show_numbers;
	private List<Integer> max;

	private int pageindex = 1;
	private int pagesize = 10;

	private Button btn_jixu;
	private Button btn_touzhu;
	private TextView footer;
	private int temp_length = 0;
	private TextView tv_secretMsg;
	private String id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_betlottey_info);
		App.activityS.add(this);
		App.activityS1.add(this);
		myAsynTask = new MyAsynTask();
		myAsynTask.execute();
		findView();
		initView();

	}

	/**
	 * myScrollView.smoothScrollTo(0,20); 初始化UI
	 */
	private void findView() {
		scrollView = (ScrollView) findViewById(R.id.scrollView);
		tv_lotteryName = (TextView) findViewById(R.id.tv_lotteryName);
		tv_money = (TextView) findViewById(R.id.tv_money2);
		tv_state = (TextView) findViewById(R.id.tv_state2);
		tv_winMoney = (TextView) findViewById(R.id.tv_winMoney2);
		tv_winMoney3 = (TextView) findViewById(R.id.tv_winMoney3);
		tv_count = (TextView) findViewById(R.id.tv_numberCount);
		tv_time = (TextView) findViewById(R.id.tv_time2);
		tv_orderId = (TextView) findViewById(R.id.tv_orderId2);
		tv_betType = (TextView) findViewById(R.id.tv_orderType2);
		tv_tishi = (TextView) findViewById(R.id.tv_wShow2);
		tv_lotteryNum = (TextView) findViewById(R.id.tv_num1);
		tv_lotteryName_issue = (TextView) findViewById(R.id.tv_lotteryName_issue);
		tv_info_tip = (TextView) findViewById(R.id.tv_info_tip);
		tv_name = (TextView) findViewById(R.id.tv_name2);
		tv_yong = (TextView) findViewById(R.id.tv_yong2);
		tv_scheme = (TextView) findViewById(R.id.tv_scheme2);
		tv_buyCount = (TextView) findViewById(R.id.tv_buy2);
		tv_title = (TextView) findViewById(R.id.tv_schemetitle2);
		//tv_content = (TextView) findViewById(R.id.tv_schemeContent2);
		tv_bei = (TextView) findViewById(R.id.tv_bei);
		img_logo = (ImageView) findViewById(R.id.img_logo);
		mListView = (MyListView2) findViewById(R.id.lv_betInfo);

		gv_winNumber = (MyGridView) findViewById(R.id.gv_winNumber);

		rl_join1 = (RelativeLayout) findViewById(R.id.rl_joinInfo);
		rl_join2 = (RelativeLayout) findViewById(R.id.rl_joinInfo2);

		btn_jixu = (Button) findViewById(R.id.btn_jixu);
		btn_touzhu = (Button) findViewById(R.id.btn_touzhu);

		betinfo_hide_btn = (ImageButton) findViewById(R.id.betinfo_hide_btn);
		ll_numberCount = (LinearLayout) findViewById(R.id.ll_numberCount);
		ll_divider = (ImageView) findViewById(R.id.ll_divider);
		btn_back = (ImageButton) findViewById(R.id.btn_back);

		tv_secretMsg = (TextView) findViewById(R.id.tv_secretMsg);

		footer = new TextView(MyCommonLotteryInfo_other.this);
		footer.setLayoutParams(new AbsListView.LayoutParams(
				LayoutParams.MATCH_PARENT, getResources()
						.getDimensionPixelSize(
								R.dimen.bet_lottery_item_title_height)));
		footer.setTextSize(14);
		footer.setGravity(Gravity.CENTER);
		footer.setTextColor(getResources().getColor(
				R.color.vpi_text_unselected_gray));
		footer.setText("下一页");
		footer.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				pageindex++;
				myAsynTask = new MyAsynTask();
				myAsynTask.execute();
			}
		});
		mListView.addFooterView(footer);

	}

	private void setWinNumber() {

		if (scheme.getLotteryID() == null)
			return;
		if (null == scheme.getWinNumber())
			return;
		Log.i("x", "彩种id   " + scheme.getLotteryID());
		Spanned number;
		String temp_win = scheme.getWinNumber().replaceAll("\\s?[\\+-]\\s?",
				"+");
		Log.i("未被替换的num", "=======" + scheme.getWinNumber());
		Log.i("被替换的num", "=======" + temp_win);
		if (!temp_win.contains("+")) {
			number = Html.fromHtml("<font color='#BE0205'>"
					+ scheme.getWinNumber() + "</FONT>");
			tv_lotteryNum.setText(number);
			return;
		}

		String red = temp_win.split("\\+")[0];
		String blue = "";

		if (temp_win.split("\\+").length == 2)
			blue = temp_win.split("\\+")[1];
		// blue = scheme.getWinNumber().split("\\+")[1];

		number = Html.fromHtml("<font color='#BE0205'>" + red + "</FONT>"
				+ "<font color='#4060ff'>" + " " + blue + "</FONT>");
		tv_lotteryNum.setText(number);
	}

	/**
	 * 给控件赋值
	 */
	private void initView() {
		btn_back.setOnClickListener(this);
		betinfo_hide_btn.setOnClickListener(this);
		ll_numberCount.setOnClickListener(this);
		btn_jixu.setOnClickListener(this);
		btn_touzhu.setOnClickListener(this);

		if (null == scheme)
			return;
		/** 合买订单状态 */
		if ("false".equalsIgnoreCase(scheme.getIsPurchasing())) {
			tv_info_tip.setText("合买投注详情");
		} else if ("true".equalsIgnoreCase(scheme.getIsPurchasing())) {
			/** 普通订单状态 */
			if (scheme.getIsChase() == 0) {
				tv_info_tip.setText("普通投注详情");
			} else {
				/** 追号订单状态 */
				tv_info_tip.setText("追号投注详情");
			}
		}
		rl_join1.setVisibility(View.GONE);
		rl_join2.setVisibility(View.GONE);
		if ("74".equals(scheme.getLotteryID())
				|| "75".equals(scheme.getLotteryID())) {
			btn_jixu.setVisibility(View.GONE);
		} else
			btn_jixu.setVisibility(View.VISIBLE);
		btn_touzhu.setText(LotteryUtils.getTitleText(scheme.getLotteryID())
				+ "投注");
		tv_lotteryName
				.setText(LotteryUtils.getTitleText(scheme.getLotteryID()));

		tv_lotteryName_issue.setText(scheme.getIsuseName() == null ? ""
				: scheme.getIsuseName() + "期");
		if (App.allLotteryLogo == null) {
			AppTools.setLogo();
		}
		img_logo.setBackgroundResource(App.allLotteryLogo.get(scheme
				.getLotteryID()));
		tv_money.setText(scheme.getMoney() + "元");
		tv_time.setText(scheme.getDateTime());
		tv_orderId.setText(scheme.getSchemeNumber());

		if (scheme.getFromClient() == 1)
			tv_betType.setText("网页投注");
		else if (scheme.getFromClient() == 2)
			tv_betType.setText("手机APP投注");

		tv_winMoney.setText("--");
		Log.i("x",
				"方案ID==" + scheme.getId() + "  是否开奖isopened=="
						+ scheme.getSchemeIsOpened() + "  是否撤单quashStatus=="
						+ scheme.getQuashStatus() + "  是否出票buyed=="
						+ scheme.getBuyed() + "  中奖金额winmoney=="
						+ scheme.getWinMoneyNoWithTax());

		tv_count.setText(scheme.getBuyContent().size() + "条");
		Log.e("x", scheme.getMultiple()+"");
		tv_bei.setText(scheme.getMultiple() + "倍");
		String status = scheme.getSchemeStatus();
		// 将设置中奖号码的方法提出来
		if (scheme.getSchemeIsOpened() != null
				&& scheme.getSchemeIsOpened().length() != 0) {
			if (scheme.getSchemeIsOpened().equals("True")) {
				setWinNumber();
			}
		}

		if (status.equals("已中奖")) {
			tv_state.setTextColor(Color.RED);
			tv_state.setText("中奖");
			setWinNumber();

			if (scheme.getDescription() != null
					&& !scheme.getDescription().equals("")) {
				String[] split = scheme.getDescription().split("加奖juejin310");
				if (split.length > 1) {
					double money_zhongjian = Arith.sub(
							scheme.getWinMoneyNoWithTax(),
							Double.parseDouble(split[1]));
					tv_winMoney.setText(money_zhongjian + "元");
					tv_winMoney3.setVisibility(View.VISIBLE);
					tv_winMoney3.setText("加奖:" + split[1]);
				} else {
					tv_winMoney.setText(scheme.getWinMoneyNoWithTax() + "元");
				}
			} else {
				tv_winMoney.setText(scheme.getWinMoneyNoWithTax() + "元");
			}

		} else {
			tv_state.setText(status);
		}

		if (0 != scheme.getQuashStatus()
				|| (scheme.getQuashStatus() + "").length() == 0) {
			tv_state.setText("已撤单");
			setWinNumber();
		} else {
			// 合买
			if (scheme.getIsPurchasing().equalsIgnoreCase("False")) {
				rl_join1.setVisibility(View.VISIBLE);
				rl_join2.setVisibility(View.VISIBLE);

				tv_name.setText(scheme.getInitiateName());
				tv_yong.setText((int) (scheme.getSchemeBonusScale() * 100)
						+ "%");
				tv_scheme.setText(scheme.getShare() + "份,共" + scheme.getMoney()
						+ "元,每份" + scheme.getShareMoney() + "元");
				tv_buyCount.setText(scheme.getMyBuyShare() + "份  共"
						+ scheme.getMyBuyMoney() + "元");
				tv_title.setText(scheme.getTitle());
				//tv_content.setText(scheme.getDescription());
			}
		}
		String numbers = scheme.getLotteryNumber();
		System.out.println("投注号码----->\n" + numbers);
		System.out.println("玩法id----" + scheme.getPlayTypeID());
		

	}

	@Override
	protected void onResume() {
		super.onResume();
		gv_winNumber.setFocusable(false);
		mListView.setFocusable(false);
		scrollView.smoothScrollTo(0, 0);
	}

	/**
	 * 异步任务
	 */
	class MyAsynTask extends AsyncTask<Void, Integer, String> {
		private ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = BaseHelper.showProgress(MyCommonLotteryInfo_other.this, null,
					"加载中", true, false);
		}

		/**
		 * 在后台执行的程序
		 */
		@Override
		protected String doInBackground(Void... params) {
			int result = 1;
			if (pageindex == 1) {
				scheme = (Schemes) getIntent().getSerializableExtra("scheme");
//				scheme=App.scheme;
				id= getIntent().getStringExtra("id");
				Log.i("x", "中奖号码=== " + scheme.getWinNumber());
				Log.i("x", "投注的倍数=== " + scheme.getMultiple());
				if (scheme == null) {
					return "-1";
				}
				List<LotteryContent> list = scheme.getBuyContent();
				// if (list == null || list.isEmpty()) {
				// return "-1";
				// }
				numbers = new String[list.size()];
				for (int i = 0; i < list.size(); i++) {
					numbers[i] = list.get(i).getLotteryNumber() + "/"
							+ list.get(i).getPlayType();
					Log.i("投注的内容numbers[" + i + "]", numbers[i]);
				}

				show_numbers = new ArrayList<String>();
				max = new ArrayList<Integer>();
				result = 0;
			}

			temp_length = Math.min(pagesize, numbers.length - pagesize
					* (pageindex - 1));

			for (int i = 0; i < temp_length; i++) {
				int index = i + pagesize * (pageindex - 1);
				show_numbers.add(numbers[index]);
				numbers[index].replace("-", "+");
				if (!numbers[index].contains("+")) {
					max.add(100);
				} else {
					max.add(numbers[index]
							.substring(0, numbers[index].indexOf("+")).trim()
							.split(" ").length);
				}
			}
			return result + "";
		}

		@Override     
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			dialog.dismiss();
			if (show_numbers != null && numbers != null) {
				footer.setText("下一页 (" + show_numbers.size() + "/"
						+ numbers.length + ")");

			}
			switch (Integer.valueOf(result)) {
			case 0:
				initView();
				adapter = new MyBetLotteryAdapter(getApplicationContext(), scheme,
						show_numbers, max);
				mListView.setAdapter(adapter);
				break;
			case 1:
				adapter.notifyDataSetChanged();
				break;
			case -1:
				MyToast.getToast(MyCommonLotteryInfo_other.this, "数据加载失败");
				break;
			}
			if (temp_length < pagesize || (numbers.length == pagesize)) {
				mListView.removeFooterView(footer);
			}
		}
	}

	@Override
	public void onClick(View arg0) {
		String lotteryID = scheme.getLotteryID();
		switch (arg0.getId()) {
		case R.id.btn_jixu:// 继续本次号码投注
			goToBetLottery(lotteryID);
			break;
		case R.id.btn_touzhu:// 去往本彩种投注
			LotteryUtils.goToSelectLottery(this, lotteryID);
			break;
		case R.id.betinfo_hide_btn:
		case R.id.ll_numberCount:
			if (!betinfo_hide_btn.isSelected()) {
				betinfo_hide_btn.setSelected(true);
				ll_divider.setVisibility(View.GONE);
				mListView.setVisibility(View.GONE);

			} else {
				betinfo_hide_btn.setSelected(false);
				ll_divider.setVisibility(View.VISIBLE);
				mListView.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.btn_back:
			finish();
			break;
		}
	}

	/**
	 * 根据彩种id跳转不同投注页面
	 * 
	 * @param lotteryID
	 *            彩种id
	 */
	private void goToBetLottery(String lotteryID) {
		System.out.println("彩种id-----" + lotteryID);
		System.out.println("玩法id-----" + scheme.getPlayTypeID());
		if (TextUtils.isEmpty(lotteryID)) {
			MyToast.getToast(MyCommonLotteryInfo_other.this, "lotteryID 为空").show();
			return;
		}
		int id = Integer.parseInt(lotteryID);
		Intent intent;
		if (!NumberTools.changeSchemesToSelectedNumbers(scheme)) {
			MyToast.getToast(MyCommonLotteryInfo_other.this, "内容记录错误").show();
			return;
		}
		Lottery mLottery = AppTools.getLotteryById(lotteryID);
		if (mLottery != null) {
			App.lottery = mLottery;
		} else {
			MyToast.getToast(this, "该奖期已结束，请等下一期").show();
			return;
		}
		switch (id) {
		case 5:// 双色球
			intent = new Intent(getApplicationContext(), BetActivity.class);
			MyCommonLotteryInfo_other.this.startActivity(intent);
			break;
		case 39:// 大乐透
			intent = new Intent(getApplicationContext(), Bet_DLT_Activity.class);
			MyCommonLotteryInfo_other.this.startActivity(intent);
			break;
		case 6:// 3D
			intent = new Intent(getApplicationContext(), BetActivityFC3D.class);
			MyCommonLotteryInfo_other.this.startActivity(intent);
			break;
		case 63:// 排列三
			intent = new Intent(getApplicationContext(), BetActivityPL3.class);
			MyCommonLotteryInfo_other.this.startActivity(intent);
			break;
		case 64:// 排列五
			intent = new Intent(getApplicationContext(),
					BetActivityPL5_QXC.class);
			MyCommonLotteryInfo_other.this.startActivity(intent);
			break;
		case 3:// 七星彩
			intent = new Intent(getApplicationContext(),
					BetActivityPL5_QXC.class);
			MyCommonLotteryInfo_other.this.startActivity(intent);
			break;
		case 13:// 七乐彩
			intent = new Intent(getApplicationContext(), Bet_QLC_Activity.class);
			MyCommonLotteryInfo_other.this.startActivity(intent);
			break;
		case 78:
		case 62:// 十一运夺金
			intent = new Intent(getApplicationContext(), Bet_11x5Activity.class);
			MyCommonLotteryInfo_other.this.startActivity(intent);
			break;
		case 70:// 11选5
			intent = new Intent(getApplicationContext(), Bet_11x5Activity.class);
			MyCommonLotteryInfo_other.this.startActivity(intent);
			break;
		case 28:// 时时彩
			intent = new Intent(getApplicationContext(), Bet_SSCActivity.class);
			MyCommonLotteryInfo_other.this.startActivity(intent);
			break;
		case 61:// 江西时时彩
			if (LotteryHelp.canToBet()) {
				if (App.list_numbers != null && App.totalCount != 0) {
					App.list_numbers.clear();
					App.totalCount = 0;
				}
				intent = new Intent(getApplicationContext(),
						JxccsBetActivity.class);
				intent.putExtra("isContinue", true);
				// 判断是几星直选。。
				int playType = scheme.getPlayTypeID();
				if (playType == 6103) {
					// lotteryNum = ""
					String lotteryNum = scheme.getBuyContent().get(0)
							.getLotteryNumber();
					String[] split = lotteryNum.split("");
					int count = 5;
					for (int i = 0; i < split.length; i++) {
						if ("-".equals(split[i])) {
							count--;
						}
					}
					playType = 61030 + count;
				}
				intent.putExtra("playType", playType);
				intent.putExtra(
						"playTypeName",
						LotteryUtils.transPlayName(playType + "",
								scheme.getLotteryNumber()));
				App.scheme=scheme;
				intent.putExtra("scheme", scheme);
				MyCommonLotteryInfo_other.this.startActivity(intent);
			} else {
				MyToast.getToast(MyCommonLotteryInfo_other.this, "该方案包含暂停的玩法，不能继续投注")
						.show();
				if (App.list_numbers != null && App.totalCount != 0) {
					App.list_numbers.clear();
					App.totalCount = 0;
				}
			}
			break;
		case 83:// 江苏快3
			intent = new Intent(getApplicationContext(), Bet_k3Activity.class);
			MyCommonLotteryInfo_other.this.startActivity(intent);
			break;
		}
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		Log.e("xxxa", "tiqu---------");
		outState.putSerializable("scheme", scheme);
		super.onSaveInstanceState(outState);
	}


	@SuppressWarnings("unchecked")
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		Log.e("xxxa", "tiqu---------11");
		if (savedInstanceState != null) {
			scheme = (Schemes) savedInstanceState.getSerializable("scheme");
		}
	}
}
